package com.wxy.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author 47868
 */
public class HelloServer {
    public static void main(String[] args) {
        //启动器 负责组装netty组件 启动服务器
        new ServerBootstrap()
                //多线程 worker和boss
                .group(new NioEventLoopGroup())
                //选择服务器的ServerSockerChannel实现
                .channel(NioServerSocketChannel.class)
                //决定了worker能执行哪些操作
                .childHandler(
                        //初始化读写通道 添加handler
                        new ChannelInitializer<NioSocketChannel>() {

                            @Override
                            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                                //添加handler
                                nioSocketChannel.pipeline().addLast(new StringDecoder());   //将ByteBuf转换为字符串
                                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {    //自定义handler处理结果
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        //打印上一步处理好的字符串
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                //监听8888
                .bind(8888);
    }
}
